/**
 * 
 */
package cn.terrence.myoauth2.server.web.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.oltu.oauth2.as.issuer.MD5Generator;
import org.apache.oltu.oauth2.as.issuer.OAuthIssuer;
import org.apache.oltu.oauth2.as.issuer.OAuthIssuerImpl;
import org.apache.oltu.oauth2.as.request.OAuthTokenRequest;
import org.apache.oltu.oauth2.as.response.OAuthASResponse;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.OAuthResponse;

/**
 * @author cuihua022
 * AccessToken Servlet
 */
public class AccessTokenBuilderServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 9137137605460798696L;

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		OAuthIssuer oauthIssuerImpl = new OAuthIssuerImpl(new MD5Generator());
		    try {
		    	OAuthTokenRequest oauthRequest = new OAuthTokenRequest(request);
		    	System.out.println(oauthRequest.getGrantType());
	            String accessToken = oauthIssuerImpl.accessToken();
	            String refreshToken = oauthIssuerImpl.refreshToken();
	            OAuthResponse r = OAuthASResponse
	                              .tokenResponse(HttpServletResponse.SC_OK)
	                              .setAccessToken(accessToken)
	                              .setExpiresIn("3600")
	                              .setRefreshToken(refreshToken)
	                              .buildBodyMessage();
		        response.setStatus(r.getResponseStatus());
		        PrintWriter pw = response.getWriter();
		        pw.print(r.getBody());
		        pw.flush();
		        pw.close();
		    }catch (OAuthSystemException e){
		    	e.printStackTrace();
		    }catch(OAuthProblemException ex) {
		        ex.printStackTrace();
		    }
	}
}
